package com.nemlistapp;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;

public class NemListDBAdapter 
{
	private static final  String DATABASE_NAME = "nemlist.db";
	private static final int DATABASE_VERSION = 1;
	static final String TABLE_NAME = "shoppingLists";
	private static Context context;
	static SQLiteDatabase db;

	private SQLiteStatement insertStatement;
	
	private static final String INSERT = "insert into "
			+ TABLE_NAME + " (shoppingListName,creationDate,completionDate,Active) values (?,?,?,?)";
	
	public NemListDBAdapter(Context context) 
	{
		NemListDBAdapter.context = context;
		OpenHelper openHelper = new OpenHelper(NemListDBAdapter.context);
		NemListDBAdapter.db = openHelper.getWritableDatabase();
		this.insertStatement = NemListDBAdapter.db.compileStatement(INSERT);
	}
	
	public long insert(String shoppingListName,String creationDate,String completionDate,String Active) 
	{
		this.insertStatement.bindString(1, shoppingListName);
		this.insertStatement.bindString(2, creationDate);
		this.insertStatement.bindString(3, completionDate);
		this.insertStatement.bindString(4, Active);
		return this.insertStatement.executeInsert();
	}
	
	public void deleteAll() 
	{
		db.delete(TABLE_NAME, null, null);
	}
	
	public List<String[]> selectAll()
	{

		List<String[]> list = new ArrayList<String[]>();
		Cursor cursor = db.query(TABLE_NAME, new String[] { "id","shoppingListName","creationDate","completionDate","Active" },
				null, null, null, null, "name asc"); 

		int x=0;
		if (cursor.moveToFirst()) {
			do {
				String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};

				list.add(b1);

				x=x+1;
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		} 
		cursor.close();

		return list;
	}
	
	public void delete(int rowId) {
		db.delete(TABLE_NAME, null, null); 
	}
	
	private static class OpenHelper extends SQLiteOpenHelper {

		OpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, shoppingListName TEXT, creationDate TEXT, completionDate TEXT, Active TEXT)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}
}
